﻿using Cap.UserMicroservice.Services;
using Cap.UserMicroservice.Services.Dtos;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;

namespace Cap.UserMicroservice.Controllers
{
    public class UserRegisterController:AbpController
    {

        public IUserService userService { get; set; }

        public ILogger<UserRegisterController> logger { get; set; }


        /// <summary>
        /// 查询用户
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetUsers")]
        public async Task<List<UserInfoDto>> GetUserAsync()
        {
            var users =  await userService.GetUsersAsync();
            return users;
        }

        /// <summary>
        /// 注册用户（消费RabbitMQ消息）
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [CapSubscribe("userRegister")]
        [NonAction]
        public async Task<string> RegisterUser(UserInfoDto userInfo)
        {
            try
            {
                var user = await userService.CreateAsync(userInfo);
                return $"注册成功..:UserName={user.Id}";
            }
            catch (Exception e)
            {
                logger.LogError("注册失败", e.Message);
                throw e;
            }
        }

        /// <summary>
        /// 注册用户失败（消费RabbitMQ消息）
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        [CapSubscribe("userRegisterFail")]
        [NonAction]
        public async Task<string> RegisterUserFail(UserInfoDto userInfo)
        {
            try
            {
                throw new Exception($"账号{userInfo.UserName}注册失败");    
                var user = await userService.CreateAsync(userInfo);
                return $"注册成功..:UserName={user.Id}";
            }
            catch (Exception e)
            {
                logger.LogError("注册失败", e.Message);
                throw e;
            }
        }

    }
}
